package com.jboost.modules.app.service.strategry.dp;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jboost.common.util.DateUtils;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.dto.resp.BdDy;
import com.jboost.modules.app.dto.resp.BdSJ;
import com.jboost.modules.app.dto.resp.DpDIanPuRep;
import com.jboost.modules.app.dto.resp.DpDingDanRep;
import com.jboost.modules.app.service.strategry.common.AbstractJdy;
import com.jboost.modules.system.entity.*;
import com.jboost.modules.system.mapper.DpDianpuMapper;
import com.jboost.modules.system.mapper.DpDingdanMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.DataUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

import static com.jboost.common.util.DateUtils.yyyyMMdd;

@Service(value = "DpDingdanQuery")
@Slf4j
public class DpDingdanQuery extends AbstractJdy<String, DpDingdan, DpDingdanMapper, DpDingdan> {


    public String getFormId() {
        return "65749d6346e135211bfb07cf";
    }

    public String getFormId1() {
        return "63f0bcda3d300400077367af";
    }

    public HttpHeaders getJdyHeaders() {
        HttpHeaders jdyHeaders = new HttpHeaders();
        jdyHeaders.set("Authorization", "Bearer " + "bdfDElitwqhraWZoCv3uxdv9PysCV605");
        return jdyHeaders;
    }

    public String getAppId() {
        return "64880dc1f3ecc50008fbae61";
    }


    @Scheduled(initialDelay = 1000, fixedRate = 300000)
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        DpDingdan hxProduct = new DpDingdan();
        sync(hxProduct);
        sync1();
        return BaseResult.success();
    }

    public void sync(DpDingdan entit) throws IOException {
        log.info("开始批量查询Hs材料数据");
        baseMapper.delete(Wrappers.lambdaQuery(DpDingdan.class).orderByDesc(BaseEntity::getId).ne(BaseEntity::getId, "0"));
        HashMap<String, Object> param = getParam();
        param.put("limit", 1000);
        List<JSONObject> jsonObjects = new ArrayList<>();
        do {
            String post = HttpRestUtils.post(query_all_api, param, getJdyHeaders());
            jsonObjects = (List<JSONObject>) JSONUtil.fromJson(post, Map.class).get("data");
            jsonObjects.forEach(e -> {
                try {
                    DpDingdan dpDingdan = JSONObject.parseObject(e.toString(), entit.getClass());
                    Object o = baseMapper.selectById(e.getString("_id"));
                    dpDingdan.setTime(sdf1.parse(e.getString("updateTime")));
                    try {
                        dpDingdan.setYw(e.getJSONObject("yw").getString("username"));
                    } catch (Exception exception) {

                    }
                    try {
                        dpDingdan.setGd(e.getJSONObject("gd").getString("username"));
                    } catch (Exception exception) {

                    }
                    try {
                        dpDingdan.setZg(e.getJSONObject("zg").getString("username"));
                    } catch (Exception exception) {

                    }
                    try {
                        dpDingdan.setBm(e.getJSONObject("bm").getString("dept_no"));
                    } catch (Exception exception) {

                    }
                    if (Objects.isNull(o)) {
                        baseMapper.insert(dpDingdan);
                    } else if (!Objects.equals(o, dpDingdan)) {
                        baseMapper.deleteById(e.getString("_id"));
                        baseMapper.insert(dpDingdan);
                    }
                } catch (Exception exception) {

                }

            });
            if (jsonObjects.size() > 0) {

                param.put("data_id", jsonObjects.get(jsonObjects.size() - 1).getString("_id"));
            }
        } while (jsonObjects.size() > 0);

    }

    public void sync1() throws IOException {
        log.info("开始批量查询Hs材料数据");
        //baseMapper.delete((Wrapper<PdmPl>) Wrappers.lambdaQuery(entit.getClass()).orderByDesc(BaseEntity::getId).ne(BaseEntity::getId,"0"));
        HashMap<String, Object> param = getParam();
        param.put("entry_id", getFormId1());
        param.put("limit", 1000);
        List<JSONObject> jsonObjects = new ArrayList<>();
        do {
            String post = HttpRestUtils.post(query_all_api, param, getJdyHeaders());
            jsonObjects = (List<JSONObject>) JSONUtil.fromJson(post, Map.class).get("data");
            jsonObjects.forEach(e1 -> {
                try {
                    DpDingDanRep.DataBean bdDy = JSONUtil.fromJson(e1.toJSONString(), DpDingDanRep.DataBean.class);
                    String qhjd = bdDy.getRemark();
                    String date = bdDy.getUpdateTime();
                    Date parse = sdf1.parse(date);
                    Date date1 = DateUtils.addDays(parse, 90);
                    if (!StringUtils.isBlank(qhjd)) {
                        if (qhjd.length() > 3) {
                            qhjd = qhjd.substring(0, 3);
                        }
                        List<DpDingdan> pdmBoms = baseMapper.selectList(Wrappers.lambdaQuery(DpDingdan.class).eq(DpDingdan::getYwsbm, qhjd));
                        if (!CollectionUtils.isEmpty(pdmBoms)) {
                            DpDingdan dpDingdan = pdmBoms.get(0);
                            DpDingDanRep.DataBeanReq dataBeanReq = DpDingDanRep.DataBeanReq.builder()._widget_1676737310454(getParaMap(dpDingdan.getYw()))
                                    ._widget_1705655613176(getParaMap(dpDingdan.getYwmc()))._widget_1702144126471(getParaMap(dpDingdan.getGd()))
                                    ._widget_1702144126472(getParaMap(dpDingdan.getZg()))
                                    ._widget_1705655613175(getParaMap(qhjd))
                                    ._widget_1705489179805(getParaMap(dpDingdan.getBmmc())).build();
                            if(Objects.nonNull(dpDingdan.getBm())){
                                dataBeanReq.set_widget_1702144126473(getParaMap(Integer.valueOf(dpDingdan.getBm())));
                            }
                            jdyUpdate1(bdDy.get_id(), dataBeanReq);
                        }
                    }

                } catch (Exception exception) {

                }

            });
            if (jsonObjects.size() > 0) {

                param.put("data_id", jsonObjects.get(jsonObjects.size() - 1).getString("_id"));
            }
        } while (jsonObjects.size() > 0);

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
       invokeStrategy();
    }


//    public void sync(DpDingdan pdmPl) throws IOException {
//        log.info("开始批量查询Hs材料数据");
//        //baseMapper.delete((Wrapper<PdmPl>) Wrappers.lambdaQuery(entit.getClass()).orderByDesc(BaseEntity::getId).ne(BaseEntity::getId,"0"));
//        HashMap<String, Object> param = getParam();
//        param.put("limit",1000);
//        List<JSONObject> jsonObjects = new ArrayList<>();
//        do {
//            String post = HttpRestUtils.post(query_all_api, param, getJdyHeaders());
//            jsonObjects   = (List<JSONObject>) JSONUtil.fromJson(post, Map.class).get("data");
//            jsonObjects.forEach(e -> {
//                try {
//                    Object o = baseMapper.selectById(e.getString("_id"));
//
//                    if (Objects.isNull(o)) {
//                        baseMapper.insert(pdmPl);
//                    }else if (!Objects.equals(o,pdmPl)){
//                        baseMapper.deleteById(pdmPl.getId());
//                        baseMapper.insert(pdmPl);
//                    }
//                }catch (Exception exception){
//
//                }
//
//            });
//            if (jsonObjects.size()>0){
//
//                param.put("data_id",jsonObjects.get(jsonObjects.size()-1).getString("_id"));
//            }
//        }while (jsonObjects.size()>0);
//
//    }
}
